package com.yeu;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UpdateTopic")
public class UpdateTopic extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateTopic() {
		super();
	}

	/** 获取真实用户IP **/
	public String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		} else {
			return request.getHeader("x-forwarded-for");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Get");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
		PrintWriter pw = response.getWriter(); // 获取 response 的输出流
		String userNumber = request.getParameter("userNumber");
		String topicContent = request.getParameter("topicContent");
		String topicImage = "222-333";
		String ipAddress = getRemortIP(request);
		//System.out.println("userNumber:" + userNumber  + "\nipAddress:" + ipAddress); // 打印出来看一看
		System.out.println("【-- 发表说说 --】");

		String resCode = "";
		String resMsg = "";
		String userId = "";

		/* 更新模块 */
		try {
			Connection connect = DBUtil.getConnect();
			Statement statement = (Statement) connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
			
			String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_TOPIC + "(userNumber,topicContent,topicImage) values('"+ userNumber + "','" + topicContent + "','" + topicImage + "')";
			if (statement.executeUpdate(sqlInsertLog) == 1) { // 插入帐号密码
				//发布成功！
				pw.print("0"); // 通过输出流把业务逻辑的结果输出
				pw.flush();
			}else {
				pw.println("发布失败"); // 通过输出流把业务逻辑的结果输出
				pw.flush();
			}
			//断开数据库连接
			statement.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}